/*
 * Copyright (c) 2011 Imre Fazekas.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the Brillien nor the names of its
 * terms and concepts may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.vii.streamline.json;

import com.vii.streamline.services.MathServices;
import com.vii.streamline.services.error.StreamLineException;
import com.vii.streamline.services.json.JsonServices;
import org.svenson.JSONProperty;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Describes a request message according to the JSON-RPC 2.0 standard
 */
public class JsonRpcRequest<P, T> {

    private String  jsonrpc;
    private String  method;
    private P       params;
    private T       id;

    private String  sessionId;

    private boolean notification;

    {
        notification = true;
    }

    public static JsonRpcRequest<Map, String> createMapRequest( String methodName ){
        JsonRpcRequest<Map, String> request = new JsonRpcRequest<Map, String>(
                JsonRpcServices.JSON_RPC_VERSION, methodName, new HashMap<String,Object>(), MathServices.newId()
        );

        return request;
    }

    public static JsonRpcRequest<Map, String> createMapRequest( String methodName, List<String> parameterNames, List<Object> parameterValues ){
        JsonRpcRequest<Map, String> request = new JsonRpcRequest<Map, String>(
                JsonRpcServices.JSON_RPC_VERSION, methodName, new HashMap<String,Object>(), MathServices.newId()
        );

        if( parameterNames != null && parameterValues != null )
            request.addParameters( parameterNames, parameterValues );

        return request;
    }

    public static JsonRpcRequest<List, String> createListRequest( String methodName, Object... parameters ){
        JsonRpcRequest<List, String> request = new JsonRpcRequest<List, String>(
                JsonRpcServices.JSON_RPC_VERSION, methodName, new LinkedList<Object>( ), MathServices.newId()
        );

        if( parameters.length > 0 )
            request.addParameters( parameters );

        return request;
    }

    public static JsonRpcRequest<List, String> createListRequest( String methodName, List parameters ){
        JsonRpcRequest<List, String> request = new JsonRpcRequest<List, String>(
                JsonRpcServices.JSON_RPC_VERSION, methodName, new LinkedList<Object>(), MathServices.newId()
        );

        if( parameters != null )
            request.setParams( parameters );

        return request;
    }


    public JsonRpcRequest() {
    }

    public JsonRpcRequest(String jsonrpc, String method, P params, T id) {
        this(jsonrpc, method, params, id, null);
    }

    public JsonRpcRequest(String jsonrpc, String method, P params, T id, String sessionId) {
        this.jsonrpc = jsonrpc;
        this.method = method;
        this.params = params;
        this.id = id;
        this.sessionId = sessionId;
    }

    public P getParams() {
        return params;
    }

    public void setParams(P params) {
        this.params = params;
    }

    public T getId() {
        return id;
    }

    public void setId(T id) {
        notification = false;
        this.id = id;
    }

    @JSONProperty( ignore = true )
    public String getRpcString() throws StreamLineException {
        return JsonServices.toJSON( this );
    }

    public String getJsonrpc() {
        return jsonrpc;
    }

    public void setJsonrpc(String jsonrpc) {
        this.jsonrpc = jsonrpc;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    @JSONProperty( ignoreIfNull = true )
    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    @JSONProperty( ignore = true )
    public boolean isNotification() {
        return notification;
    }

    public void addParameter(String name, Object value){
        ((Map)params).put(name, value);
    }

    public void addParameters(Object... os){
        for( Object o : os )
            ((List)params).add( o );
    }

    public void addParameters(List<String> parameterNames, List<Object> parameterValues){
        for( int i=0;i<parameterValues.size(); ++i ){
            addParameter( parameterNames.get(i), parameterValues.get(i) );
        }
    }

    public void replaceParameters(List<String> parameterNames, List<Class> parameterTypes) throws StreamLineException {
        HashMap params = new HashMap();

        List _values = (List)this.getParams();

        if( _values.size() != parameterNames.size() ){
            /*
            if( parameterTypes.get( parameterTypes.size()-1 ).isArray() && _values.size()>=parameterTypes.size()-1 ){
                try{
                    Object array = Array.newInstance( parameterTypes.get( parameterTypes.size()-1 ).getComponentType(), (_values.size() - (parameterTypes.size()-1) ) );
                    for( int i=parameterTypes.size()-1, j=0; i<_values.size(); ++i, ++j ){
                        Array.set( array, j, _values.get(i) );
                    }
                    while( _values.size()>parameterTypes.size()-1 ){
                        _values.remove( _values.get( _values.size()-1 ) );
                    }
                    _values.add( array );
                } catch (Exception e){
                    e.printStackTrace();
                    throw new StreamLineException( JsonRpcServices.ERROR_INVALID_PARAMS.getCode(), JsonRpcServices.ERROR_INVALID_PARAMS.getMessage() );
                }
            }
            else
            */
            throw new StreamLineException( JsonRpcServices.ERROR_INVALID_PARAMS.getCode(), JsonRpcServices.ERROR_INVALID_PARAMS.getMessage() );
        }

        for( int i=0; i<parameterNames.size(); ++i ){
            params.put( parameterNames.get( i ), _values.get(i) );
        }

        setParams((P) params);
    }

    @Override
    public String toString() {
        return "JsonRpcRequest{" +
                "id=" + id +
                ", params=" + params +
                ", method='" + method + '\'' +
                ", jsonrpc='" + jsonrpc + '\'' +
                '}';
    }

}
